﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.PowerShell;

using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Cmdlet;

namespace Community.SharePoint.PowerShell
{
    /// <summary>
    /// SharePoint PowerShell Community Kit
    /// This cmdlet creates adds a scope to a scope display group given 
    /// ScopeDisplayGroupPipeBind and ScopePipeBind
    /// Future Commands: Set-SPEnterpriseSearchQueryScopeDisplayGroupDefault
    ///                  Remove-SPEnterpriseSearchQueryScopeDisplayGroup
    ///                  Get-SPEnterpriseSearchQueryScopeDisplayGroup
    /// Example (Adds two scopes to the scope display group "New Scope Display Group" setting "People" as the default): 
    /// $searchapp = Get-SPEnterpriseSearchServiceApplication "Search Service Application"
    /// $group = New-SPEnterpriseSearchQueryScopeDisplayGroup -Name "New Scope Display Group" -url http://sp2010 -SearchApplication $searchapp
    /// $scope = Get-SPEnterpriseSearchQueryScope -Identity "My Scope" -SearchApplication $searchapp
    /// New-SPEnterpriseSearchQueryScopeDisplayGroupScope -ScopeDisplayGroup $group -Scope $Scope
    /// $scope = Get-SPEnterpriseSearchQueryScope -Identity "People" -SearchApplication $searchapp
    /// New-SPEnterpriseSearchQueryScopeDisplayGroupScope -ScopeDisplayGroup $group -Scope $Scope -default $true
    /// Author: Corey Roth (coreyroth@gmail.com)
    /// Creation Date: 8/9/2010
    /// http://www.dotnetmafia.com
    /// </summary>
    [Cmdlet(VerbsCommon.New, "SPEnterpriseSearchQueryScopeDisplayGroupScope")]
    public class NewEnterpriseSearchQueryScopeDisplayGroupScope : SPNewCmdletBase<ScopeDisplayGroup>
    {
        [Parameter(Mandatory = true, ValueFromPipeline = true, Position=0), Alias(new string[] { "g" })]
        public ScopeDisplayGroupPipeBind ScopeDisplayGroup { get; set; }

        [Parameter(Mandatory = true, ValueFromPipeline = true), Alias(new string[] { "s" })]
        public ScopePipeBind Scope { get;  set; }

        [Parameter(Mandatory = false), DefaultValue(true)]
        public bool? Default { get; set; }

        protected override ScopeDisplayGroup CreateDataObject()
        {
            ScopeDisplayGroup scopeDisplayGroup = ScopeDisplayGroup.Read();
            Scope scope = Scope.Read();

            // petecuttriss - add the scope to the display group if it doesn't exist
            if (scopeDisplayGroup.Contains(scope))
                scopeDisplayGroup.Add(scope);

            // if the user wants the value to be the default, set it
            if ( (Default.HasValue) && (Default.Value))
            {
                scopeDisplayGroup.Default = scope;
            }

            scopeDisplayGroup.Update();

            return scopeDisplayGroup;
        }
    }
}
